#from Gui import *
import ctypes
import threading
import math
import time
import os
import pygame
from pygame.locals import *
import ctypes
from Tkinter import *
SET_SERVO = 1
KILL_CREEPA = 2
TOWERTIMEARRAY = 3
KILL_CREEPB = 4
GET_RA0 = 5
FIRING = 6
GET_TOWERTYPE = 7
GET_TOWERPOS = 8
GET_TICK = 9
UNKILL_CREEPA = 10
UNKILL_CREEPB = 11
#[(32, 16, math.pi/4),(29, 24, 13*math.pi/12),(29, 33, math.pi/24),(9, 34, 23*math.pi/24),(17, 21.5, 13*math.pi/12),(9, 12, -math.pi/4)]


usb = ctypes.cdll.LoadLibrary('usb.dll')
usb.initialize()

buffer = ctypes.c_buffer(8)

def update_clock():
    usb.control_transfer(dev, 0xC0, GET_TICK, 0, 0, 1, buffer)
    tick = ord(buffer[0])
    return tick
    #update_clock()

def update_creep():
    usb.control_transfer(dev, 0xC0, GET_CREEP, 0, 0, 1, buffer)
    creep = ord(buffer[0])
    return creep
    
    
def bits(i,n): 
    return tuple((0,1)[i>>j & 1] for j in xrange(n-1,-1,-1)) 
def get_towerpos():
    usb.control_transfer(dev, 0xC0, GET_TOWERPOS, 0, 0, 1, buffer)
    towertype = ord(buffer.raw[0])
    return (bits(towertype,8), towertype)
    #root.after(50, update_status)

def kill(value):
    print "kill_spot is %s" %value
    if value < 8:
        usb.control_transfer(dev, 0x40, KILL_CREEPA, int(value), 0, 0, buffer)
    else:
        usb.control_transfer(dev, 0x40, KILL_CREEPB, int(value-8), 0, 0, buffer)
        
def unkill(value):
    print "kill_spot is %s" %value
    if value < 8:
        usb.control_transfer(dev, 0x40, UNKILL_CREEPA, int(value), 0, 0, buffer)
    else:
        usb.control_transfer(dev, 0x40, UNKILL_CREEPB, int(value-8), 0, 0, buffer)



tower_delays = ctypes.c_buffer(64)

def update_towers(time_list, firing_array): 
    firing_byte = 0
    for j in range(len(firing_array)):
        firing_byte += (2**j)*firing_array[7-j]
    for i in range (8):
        val = int(70.*int(time_list[i])/256+45)
        #print val
        tower_delays[i] = chr(val)
    usb.control_transfer(dev, 0x40, TOWERTIMEARRAY, 0, 0, len(tower_delays), tower_delays)
    usb.control_transfer(dev, 0xC0, FIRING, firing_byte, 0, 1, buffer)

def distance(p1, p2):
    return math.sqrt(math.pow((p1[0] -p2[0]),2)+math.pow((p1[1] -p2[1]),2))

def determine_tangent(c1, c2):
    """ c1 and c2 are two circles, each represented by triple (x,y,r) where x,y are center coordinates
    and r is the radius. Assuming c1 is the circle with smaller radius, this function returns all
    possible tangents (0-4) between these two circles. """
    x1,y1,r1 = c1
    x2,y2,r2 = c2
    assert(r1<=r2)
    d = math.sqrt((x1-x2)**2 + (y1-y2)**2)
    assert(d>0)
    direction_from_c1_to_c2 = ((x2-x1),(y2-y1))

    outer_tangent = []
    inner_tangent = []
    if r2 - r1 > d:
        print "case 0: c1 is inside c2, hence no tangent"
        return outer_tangent, inner_tangent
    if r2 - r1 == d:
        print """case 1: c1 is inscribed in c2
            return only 1 tangent line determined by the touching point and direction"""
        touch_point = (x1 - r1*(x2-x1)/d, \
                       y1 - r1*(y2-y1)/d)
        direction = (y2-y1, x2-x1)
        point_1 = (touch_point[0] + r2*direction[0]/d, \
                   touch_point[1] + r2*direction[1]/d)
        point_2 = (touch_point[0] - r2*direction[0]/d, \
                   touch_point[1] - r2*direction[1]/d)
        #outer_tangent = (touch_point,direction)
        outer_tangent.append((point_1, point_2))
        return outer_tangent, inner_tangent

    cos_theta = (r1-r2)/d  # rotation_angle >= pi/2
    sin_theta = math.sqrt(1 - (cos_theta)**2)
    for i in (-1,+1):
        direction = (cos_theta*(x2-x1) + i*sin_theta*(y2-y1), \
                         -i*sin_theta*(x2-x1)+cos_theta*(y2-y1))
        tangent_point_1 = (x1 + r1*direction[0]/d, \
                           y1 + r1*direction[1]/d)
        tangent_point_2 = (x2 + r2*direction[0]/d, \
                           y2 + r2*direction[1]/d)
        outer_tangent.append((tangent_point_1, tangent_point_2))

    if r1 + r2 > d:
        print """case 2: the two circles intersect, hence no inner tangent
          return the two outer tangent lines determined by tangent points"""
        return outer_tangent, inner_tangent

    if r1 + r2 == d:
        print """ case 3: the two circles touch each other
         return the two outer tangent lines plus one additional inner tangent
         line determined by the touching point and direction """
        touch_point = (x1 + r1*(x2-x1)/d, \
                       y1 + r1*(y2-y1)/d)

        direction = (y2-y1,x2-x1)
        direction = (y2-y1, x2-x1)
        point_1 = (touch_point[0] + r2*direction[0]/d, \
                   touch_point[1] + r2*direction[1]/d)
        point_2 = (touch_point[0] - r2*direction[0]/d, \
                   touch_point[1] - r2*direction[1]/d)
        #inner_tangent = (touch_point, direction)
        inner_tangent.append((point_1, point_2))

        return outer_tangent, inner_tangent

##    print  """case 4: the two circles are separated
##     return the two outer and two inner tangent lines
##     all determined by the tangent points"""
    cos_theta = (r1+r2)/d  # rotation_angle <= pi/2
    sin_theta = math.sqrt(1 - (cos_theta)**2)
    for i in (-1,+1):
        direction = (cos_theta*(x2-x1) + i*sin_theta*(y2-y1), \
                         -i*sin_theta*(x2-x1)+cos_theta*(y2-y1))

        tangent_point_1 = (x1 + r1*direction[0]/d, \
                           y1 + r1*direction[1]/d)

        tangent_point_2 = (x2 - r2*direction[0]/d, \
                           y2 - r2*direction[1]/d)

        inner_tangent.append((tangent_point_1, tangent_point_2))

    return outer_tangent, inner_tangent



def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()


class Board:
    oldtime=0;
    newtime=0;
    creepkilltime=2;
##    hardgears = [(34.25,4.75,1.25),(34.,18.75,1.75),(21.25,21.,1.5),
##                    (34.25,35.75,1.5),(4.75,35.,1.25),(14.25,14.75,1.25),
##                    (5.,4.5,2.5)]
    hardgears = [(5.5,4.5,1.25),(34.125,5,1.25),(33.75,18.75,1.25),(21,21.25,1.5),(35.25,33.25,1.5),(4.75,34.75,2),(14,14.75,2.5)]
    gear_tangents = [1,1,3,2,1,3,2]
    gear_directions = [-2,1,1,0,1,-1,1]
    hardkillerdistances = [ 3200/16*(i+1) for i in xrange(16)]
    display_size=(800,800)
    numcreeps=16
    numtowers=6
    numkillers=16
    creep_path = []
    cum_dist = []
    gearscale=20

    currentkilling=[]    
    
    first_pos=0
    creep_sep = 6.75
    def __init__(self):
        for i in xrange(Board.numkillers):
            unkill(i)
        gearscale=Board.gearscale
        #window position
        #must be before initialise pygame
        window_x = 0
        window_y = 10
        self.tick_list = []
        self.rate= 50
        os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (window_x,window_y)

        #end window position setting        
        pygame.init()
        self.screen = pygame.display.set_mode(Board.display_size)
        pygame.display.set_caption('POE TIME')
        pygame.mouse.set_visible(0)        
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        
        self.creeps=[Creep(i) for i in xrange(Board.numcreeps)]
        self.creepsprites = pygame.sprite.RenderPlain(self.creeps)
        
        self.towers = [Tower(i) for i in xrange(Board.numtowers)]
        self.towersprites = pygame.sprite.RenderPlain(self.towers)
        #self.allsprites = pygame.sprite.RenderPlain( (Gear((100,50,10), 0,90), Gear((200,100,50), 0,90), Creep() ) )

        Board.hardgears = [(Board.gearscale*g[0],Board.gearscale*g[1],Board.gearscale*g[2]) for g in Board.hardgears]
        self.setup_path()
        self.gearsprites=pygame.sprite.RenderPlain(self.gears)
        self.background.fill((255, 255, 255))

                
        if pygame.font:
            font = pygame.font.Font(None, 36)
            text = font.render("POE: GET SUM", 1, (10, 10, 10))
            textpos = text.get_rect(centerx=self.background.get_width()/2)
            self.background.blit(text, textpos)

            
        
        
        #print Board.creep_path
        #[[p[0]*gearscale, p[1]*gearscale] for p in Board.creep_path]
        self.gearsprites.draw(self.background)
        for i in xrange(len(Board.gear_tangents)):
            pygame.draw.line(self.background,(255*Board.gear_tangents[i]/3,255-Board.gear_tangents[i]/3,0),Board.creep_path[2*i],Board.creep_path[2*i+1], 2)
        
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()
        self.clock = pygame.time.Clock()
        
                
        self.infiniteloop()

    def infiniteloop(self):
        while 1:
            #self.clock.tick(30)
            
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                elif event.type == KEYDOWN and event.key == K_ESCAPE:
                    return
            self.update();
            
            self.draw();
            pygame.display.flip()

#mainupdate            
    def update(self):
        Board.newtime=time.clock()
        #self.gears[0].update()
        #Board.gear_tangents=[int(Board.newtime)%4]*7
        #self.setup_path()
        #Board.first_pos=(Board.first_pos+1)%Board.cum_dist[-1]
        Board.first_pos = self.get_time()
        #for creep in self.creeps:
        #    creep.update()
        #self.gearsprites.update()
        #self.towersprites.update()
        self.towerpos,towerposint = get_towerpos()
        #print "towerpos:",self.towerpos," inty:", towerposint
        self.towerpos=[1,1,1,1,1,1]
        for i in range(Board.numtowers):
            self.towers[i].activated=self.towerpos[i]
            
                #self.towers[i] = Tower(
        
        delay_array = []
        firing_array = []
        for creep in self.creeps:
            if creep.beenKilled == False:
                self.updateCreepXY(creep)
                if creep.isDead():
                    self.kill_creep(creep)
        for creep, i in self.currentkilling:
            if creep.distance<Board.hardkillerdistances[i]+6.75/2:
                unkill(i)
                self.currentkilling.remove((creep,i))
                creep.beenKilled=True
                if creep in self.creeps:
                    self.creeps.remove(creep)
                self.creepsprites.remove(creep)
                
                
                    
        for i in range(Board.numtowers):
            firing = 0
            if self.towerpos[i]:
                delay, firing = self.towers[i].update(self.creeps)
                delay_array.append(delay)
            else:
                delay_array.append( self.towers[i].angle)
            firing_array.append( 1)#replaced 1 for firing
        firing_array.append(0)
        firing_array.append(0)
        delay_array.append(80)
        delay_array.append(80)
        update_towers(delay_array, firing_array)
        
        #creep.moveTo(Board.creep_path[-1][0],Board.creep_path[-1][1])
        #self.creeps[0].moveTo(self.gears[0].start_point[0], self.gears[0].start_point[1])
        #print self.gears[0].end_theta*180/math.pi
        #self.creepsprites.update()
        
        Board.oldtime=Board.newtime
        #self.allsprites.update()
##        for tower in self.towers:
##            tower.update()
##
##        self.creep_pos = []
##        for creep in self.creeps:
##            (x,y) = self.creepPath.get_xy_pos(time.clock(), creep.num)
##            creep.x = 100+10*x
##            creep.y = 600-10*y
##            self.creep_pos.append((creep.x,creep.y))
            #c = towergui.canvas.create_oval((creep.x, creep.y),fill='black', width = 3)
            
            
        
            
    def draw(self):
        #print [(creep.distance) for creep in self.creeps]
        #print Board.cum_dist
        #self.screen.blit(self.background, (0, 0))
        #self.gearsprites.clear(self.screen, self.background)
        self.towersprites=pygame.sprite.RenderPlain([tower for tower in self.towers if tower.activated])
        self.towersprites.clear(self.screen, self.background)
        self.creepsprites.clear(self.screen, self.background)
        #self.gearsprites.draw(self.screen)
        self.towersprites.draw(self.screen)
##        for tower in self.towers:
##            if tower.activated:
##                tower.draw(self.screen)
        self.creepsprites.draw(self.screen)

    def get_time(self):
        if update_clock():
            t=time.clock()
            self.tick_list.append(t)
            print len(self.tick_list)
            if len(self.tick_list)>1:
                self.rate = len(self.tick_list)*6.75/(self.tick_list[-1]-self.tick_list[0])
        if len(self.tick_list)>0:
            self.dist = len(self.tick_list)*6.75 + (time.clock()-self.tick_list[-1])*self.rate
        else:
            self.dist = self.rate * time.clock()
        return self.dist
        

    def setup_path(self):
        #each gear is x,y,r
        #x,y position
        #r is radius of the gear
        Board.creep_path=[]
        next_pos = (Board.hardgears[0][0],Board.hardgears[0][1])
        for i in range(len(Board.hardgears)-1)+[-1]:
            c1= Board.hardgears[i]
            c2 = Board.hardgears[i+1]
            if (c2[2]<c1[2]):
                c3=c2
                c2=c1
                c1=c3
            outer_tangent, inner_tangent = determine_tangent(c1, c2)
            outer_tangent+=inner_tangent;
            nextpos_choices = outer_tangent[Board.gear_tangents[i]]
            if (math.pow((nextpos_choices[0][0] -next_pos[0]),2)+math.pow((nextpos_choices[0][1] -next_pos[1]),2)<math.pow((nextpos_choices[1][0] -next_pos[0]),2)+math.pow((nextpos_choices[1][1] -next_pos[1]),2)):
                Board.creep_path.append(nextpos_choices[0])
                next_pos = nextpos_choices[1]
                Board.creep_path.append(next_pos)
            else:
                Board.creep_path.append(nextpos_choices[1])
                next_pos = nextpos_choices[0]
                Board.creep_path.append(next_pos)


        self.gears =  []#[Gear((Board.hardgears[i][0],Board.hardgears[i][1],Board.hardgears[i][2]), 0,90) for i in xrange(len(Board.hardgears))]

        #print Board.creep_path
        sum = 0
        numgears=len(Board.hardgears)
        for i in xrange(numgears):
            point_end=Board.creep_path[i*2]
            point_start=Board.creep_path[i*2-1]
            point_next_start=Board.creep_path[i*2+1]
            
            g=Gear(Board.hardgears[i],point_start, point_end, Board.gear_directions[i])
            self.gears.append(g)
            if Board.gear_directions[i]==1 :
                
                sum+=g.r*abs(g.start_theta-g.end_theta)
            elif (Board.gear_directions[i]==0 or Board.gear_directions[i]==-1 or Board.gear_directions[i]==-2):
##                print "YOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",i
##                print g.r*abs(g.start_theta-g.end_theta)
##                print g.r*(2*math.pi-abs(g.start_theta-g.end_theta))
                sum+=g.r*(2*math.pi-abs(g.start_theta-g.end_theta))
            
            Board.cum_dist.append(sum)
            
            sum+=distance( point_end, point_next_start)
            Board.cum_dist.append(sum)
        print Board.cum_dist
            

    def updateCreepXY(self,creep):
        creep.distance=(Board.first_pos-Board.creep_sep*creep.num*Board.gearscale)%Board.cum_dist[-1]
        i=0
        for j in xrange(len(Board.cum_dist)):
            if (creep.distance<Board.cum_dist[j]):
                break;
            i+=1
        diff=(creep.distance-Board.cum_dist[i-1])/(Board.cum_dist[i]-Board.cum_dist[i-1])
        if i==0:
            #print self.gears[0].start_theta*180/math.pi, self.gears[0].end_theta*180/math.pi
            diff= (creep.distance/Board.cum_dist[0])
        if (i%2==0):
            g=self.gears[i/2]
            theta=g.start_theta+diff*(g.end_theta-g.start_theta)
            if (g.direction==-1):
                theta=g.start_theta+diff*(2*math.pi-(g.start_theta-g.end_theta))
            elif (g.direction == 0):
                theta=g.start_theta-diff*(2*math.pi-abs(g.start_theta-g.end_theta))
            elif(g.direction == -2):
                theta=g.start_theta+diff*((math.pi*2-g.start_theta+g.end_theta))
            creep.moveTo(g.x+g.r*math.cos(theta), g.y+g.r*math.sin(theta))
        else:
            g=self.gears[i/2]
            g2=self.gears[(i/2+1)%len(self.gears)]
            creep.moveTo(g.end_point[0]+diff*(g2.start_point[0]-g.end_point[0]),g.end_point[1]+diff*(g2.start_point[1]-g.end_point[1]))
            
    def kill_creep(self, creep):
        dist = creep.distance
        for i in xrange(Board.numkillers):
            if ( Board.hardkillerdistances[i]> dist and Board.hardkillerdistances[i] < dist+6.75*Board.gearscale):
                #creep.beenKilled=True
##                threadkill=threading.Thread(target=self.kill_creep_thread, args=(i, creep))
##                threadkill.start()
                kill(i)
                self.currentkilling.append((creep,i))
                
    def kill_creep_thread(self,num, creep):
        kill(num)
        killtime=time.clock()+Board.creepkilltime
        while (time.clock()<killtime):
            pass
        kill(num)
        
        
class Gear(pygame.sprite.Sprite):
    def __init__(self, (x,y,r), point_start=[0,0], point_end=[0,0], direction=True):
        pygame.sprite.Sprite.__init__(self)
        #self.image, self.rect = load_image('O.GIF', -1)
        self.x = x
        self.y = y
        self.r = r
        self.start_point = point_start
        self.end_point = point_end
        self.start_theta=math.atan2((point_start[1]-y),(point_start[0]-x))
        self.end_theta=math.atan2((point_end[1]-y),(point_end[0]-x))
        self.direction=direction

        self.rect = pygame.Rect(x-r,y-r,r*2,2*r)
        self.image = pygame.Surface(self.rect.size)
        self.image.fill((255, 255, 255))
        #self.image = pygame.transform.smoothscale(self.image, self.rect.size )
        pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), r, 3)
        
        #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), 2)
        #print self.rect

##        self.dx=1
##        
##    def update(self):
##        #print self.rect.centerx
##        #self.rect.centerx += (Board.newtime-Board.oldtime)*10
##        #print self.rect.move(((Board.newtime-Board.oldtime)*10, 0)).center
##       #self.rect = self.rect.move(((Board.newtime-Board.oldtime)*10, 0))
##        self.rect.centerx += self.dx;
##        if (self.rect.right> 800) or (self.rect.left <0):
##            self.dx*=-1
##        #print "new:",self.rect.center
        def getRadius():
            return self.r
        
class Creep(pygame.sprite.Sprite):
    size=20
    def __init__(self, num=0, HP=10):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('creep.jpg', -1)
        self.num=num
        self.HP = HP
        self.x=250
        self.y=50
        self.distance=0;
        self.rect.center = (self.x, self.y)
        self.beenKilled = False

        self.rect = pygame.Rect(self.x,self.y,Creep.size,Creep.size)
        self.image = pygame.transform.smoothscale(self.image, self.rect.size )
        
    def hurt(self,HPloss):
        self.HP-=HPloss
        self.image = pygame.transform.flip(self.image, False, True)
        return self.HP>0
   # def update():
        
    def isDead(self):
        return self.HP<=0
    
            
    def moveTo(self, x,y):
        self.x=x
        self.y=y
        self.rect.centerx = x
        self.rect.centery = y
        
class Tower(pygame.sprite.Sprite):
    numtowerspots=6;
    numtowers=0;
    hardtowers = [(32, 16, math.pi/4),(29, 24, 13*math.pi/12),(29, 33, math.pi/24),(9, 34, 23*math.pi/24),(17, 21.5, 13*math.pi/12),(9, 12, -math.pi/4)]
    tower_type_names = ['Water', 'Wind', 'Fire', 'Power', 'Awesrome', 'NoahtyestolemyPoEproject']
    tower_ranges = [5000]*numtowerspots
    tower_damges = [5]*numtowers
    tower_size = 50;
    neutral = 80
    
    def __init__ (self, num =0, ttype = 0):
        #towersetup
        #tsu
        pygame.sprite.Sprite.__init__(self)
        self.num = num
        self.activated = False
        self.x = Tower.hardtowers[num][0]*Board.gearscale
        self.y = Tower.hardtowers[num][1]*Board.gearscale
        self.default_angle = Tower.hardtowers[num][2]
        self.angle = 80
        self.type = ttype
        self.range = 70#tower_ranges[self.type]
        self.damage = 10#tower_damages[self.type]
        self.target = None#but don't shoot at it till it's in range!
        self.lastfired = time.clock()
        self.firing = False
        self.delay = 2
        
        self.image, self.rect = load_image('tower.png', -1)
        self.rect.center = (self.x, self.y)
        #self.image, self.rect = load_image('O.GIF', -1)

        self.rect = pygame.Rect(self.x,self.y,Tower.tower_size,Tower.tower_size)
        #self.image = pygame.Surface(self.rect.size)
        #self.image.fill((255, 255, 255))
        self.image = pygame.transform.smoothscale(self.image, self.rect.size )
        #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), r/2, 3)
        
        #pygame.draw.circle(self.image, (0, 0, 0), (self.rect.width/2, self.rect.height/2), 2)
        

    def __str__(self):
        print 'This', tower_type_names[self.type], 'tower is located at (', self.rect.centerx, ',', self.rect.centery, ').'

    def update(self, creeps):
        #is the current creep dead?
            
        #if not self.target or self.target.isDead():
        #if so, find a new creep
        self.target=self.selecttarget( creeps )
        if self.target:
            self.aim(self.target)
            
        timesincelastfire = time.clock() - self.lastfired
        if self.target and not self.target.isDead() and (  timesincelastfire> self.delay):
            self.firing = True
            self.target.hurt(self.damage)
            print "HIIIITTTTT!!!"
            self.image = pygame.transform.flip(self.image, False, True)
            self.lastfired=time.clock()
        else:
            self.firing = False
        print timesincelastfire
        
        #self.image.fill((255,0,0, 0), [0,0,timesincelastfire/self.delay*self.image.get_width(),timesincelastfire/self.delay*self.image.get_height()])

        return self.angle, self.firing

    def selecttarget(self, creeps):
        #Choose the first living creep in range
        for creep in creeps:
            if not creep.isDead():
                if math.sqrt( (creep.x - self.x)**2 + (creep.y - self.y)**2) <= self.range:
                    return creep
                #else:
                   # print math.sqrt( (creep.x - self.x)**2 + (creep.y - self.y)**2), self.range
        return None

    def aim(self, creep):
        self.angle = rad_to_delay(math.atan2(creep.x - self.x, creep.y - self.y) - self.default_angle)
        #print "aimed ",self.num," at:",self.angle
        #convert to duty cycle and send a vendor request to the pic
          
def rad_to_delay(angle): #0 - 2pi --> 45 - 135 = ~240deg
    angle = angle%(2*math.pi)
    if 0 < angle < math.pi/3:
        return 55*angle + 80
    if math.pi/3 < angle <= math.pi/2:
        return 135
    if math.pi/2 < angle < 2*math.pi/3:
        return 25
    if 2*math.pi/3 < angle < 2*math.pi:
        return 55*(angle-2*math.pi/3) + 25
if __name__ == '__main__':
    dev = usb.open_device(0x6666, 0x0003, 0)
    if dev<0:
        print "No matching device found...\n"
    else:
        ret = usb.control_transfer(dev, 0x00, 0x09, 1, 0, 0, buffer)
        if ret<0:
            print "Unable to send SET_CONFIGURATION standard request.\n"
    Board()
    usb.close_device(dev)
